'''
Created on Dec 20, 2010

@author: dexen
'''

import sqlite3 as lite
import cPickle

from dexen.system.common.base import Action
from dexen.system.server.archive_mgr import ArchiveMgr
from dexen.system.common.transact import Transaction, MasterRecvTransact
from dexen.system.server import db
from dexen.system.common.meta import JobMeta

class ActionMgr(object):
    def __init__(self, job_meta):
        self.actions = []
        self.job_meta = job_meta
        self.archive_mgr = ArchiveMgr(job_meta)
    
    def _process(self, actions):
        archive_mgr = self.archive_mgr
        assert isinstance(archive_mgr, ArchiveMgr)
        jm = self.job_meta
        assert isinstance(jm, JobMeta)

        conn = db.get_connection()

        c = conn.cursor()
        assert isinstance(c, lite.Cursor)
        
        for action in actions:
            assert isinstance(action, Action)
            transact = action.get_transact()
            assert isinstance(transact, Transaction)
            inds = transact.get_inds()
            archive_mgr.archive_inds(inds)
            transact.set_inds(inds) # Needed to replace inds back with stripped archive version
            if isinstance(transact, MasterRecvTransact):
                assert isinstance(transact, MasterRecvTransact)
                archive_mgr.archive_master(transact.get_archive())
                transact.strip_archive()
            
            """
            pickled = cPickle.dumps(action)
            c.execute("INSERT INTO Action VALUES(?,?,?)",
                (action.get_id(), pickled, jm.get_id())
            )"""
            
        #conn.commit()
        c.close()
    
    # called by core thread        
    def add_actions(self, actions):
        self.actions.extend(actions)
        self._process(actions)

    # called by service thread
    def get_actions(self, act_id):
        #act_id refers to the last id that the client has received
        acts = []
        for i, action in enumerate(self.actions[act_id:]):
            assert isinstance(action, Action)
            assert action.get_id() == act_id + i+1 #act_id starts from 1, list index starts from 0
            acts.append(action)
        return acts
    
    # called by service thread
    def get_ind_archive(self, ind_id, name):
        return self.archive_mgr.get_ind_archive(ind_id, name)
    
    # called by service thread
    def get_ind_archive_all(self, ind_id):
        return self.archive_mgr.get_ind_archive_all(ind_id)
    
    # called by service thread
    def get_ind_archive_names(self, ind_id):
        return self.archive_mgr.get_ind_archive_names(ind_id)
    
    def on_delete(self):
        self.archive_mgr.delete_all()
        
        
